{% extends 'base.html' %}

{% block title %}首次配置 | Tiny QA{% endblock %}

{% block head %}
<style>
.welcome-section {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    padding: 3rem 0;
    margin-bottom: 2rem;
}

.config-card {
    border: none;
    box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
    border-radius: 1rem;
}

.form-control:focus {
    border-color: #667eea;
    box-shadow: 0 0 0 0.2rem rgba(102, 126, 234, 0.25);
}

.btn-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    padding: 0.75rem 2rem;
    border-radius: 0.5rem;
    font-weight: 600;
}

.btn-primary:hover {
    background: linear-gradient(135deg, #5a6fd8 0%, #6a4190 100%);
    transform: translateY(-1px);
}

.feature-item {
    padding: 1rem;
    border-radius: 0.5rem;
    background: #f8f9fa;
    margin-bottom: 1rem;
}

.feature-item i {
    color: #667eea;
    font-size: 1.5rem;
    margin-right: 0.5rem;
}
</style>
{% endblock %}

{% block content %}
<!-- 欢迎区域 -->
<div class="welcome-section">
    <div class="container text-center">
        <h1 class="display-4 mb-3">欢迎使用 Tiny QA</h1>
        <p class="lead mb-0">智能知识库问答系统</p>
        <p class="mb-0">请完成以下配置以开始使用</p>
    </div>
</div>

<div class="container">
    <div class="row justify-content-center">
        <div class="col-lg-8">
            <!-- 配置卡片 -->
            <div class="card config-card">
                <div class="card-header bg-primary text-white text-center">
                    <h4 class="mb-0"><i class="bi bi-gear-fill me-2"></i>系统配置</h4>
                </div>
                <div class="card-body p-4">
                    <form id="first-run-form">
                        <!-- 文档目录配置 -->
                        <div class="mb-4">
                            <h5 class="text-primary mb-3">
                                <i class="bi bi-folder-fill me-2"></i>文档目录配置
                            </h5>
                            <div class="alert alert-info">
                                <i class="bi bi-info-circle me-2"></i>
                                <strong>重要提示：</strong>请指定包含您文档的本地目录路径。系统将自动扫描并处理该目录中的所有支持格式的文档。
                            </div>
                            
                            <div class="mb-3">
                                <label for="documents_path" class="form-label fw-bold">文档目录路径</label>
                                <div class="input-group">
                                    <input type="text" class="form-control" id="documents_path" 
                                           name="documents_path" required 
                                           placeholder="请输入本地文档目录的完整路径">
                                    <button class="btn btn-outline-secondary" type="button" id="help-btn">
                                        <i class="bi bi-question-circle"></i> 帮助
                                    </button>
                                </div>
                                <div class="form-text">
                                    <strong>支持的文档格式：</strong>PDF (.pdf), Word (.docx), Excel (.xlsx), 文本 (.txt), Markdown (.md)
                                </div>
                                <div class="alert alert-info mt-2">
                                    <i class="bi bi-info-circle me-2"></i>
                                    <strong>Docker环境说明：</strong>请输入您本地主机的文档目录路径，系统将自动建立卷映射关系。
                                </div>
                            </div>
                            
                            <!-- 路径验证结果 -->
                            <div id="path-validation" class="d-none">
                                <div id="validation-result"></div>
                                <div id="file-count" class="mt-2"></div>
                            </div>
                        </div>

                        <!-- 分块配置 -->
                        <div class="mb-4">
                            <h5 class="text-primary mb-3">
                                <i class="bi bi-puzzle-fill me-2"></i>文档分块配置
                            </h5>
                            <div class="row">
                                <div class="col-md-6">
                                    <label for="chunk_size" class="form-label">分块大小</label>
                                    <input type="number" class="form-control" id="chunk_size" 
                                           name="chunk_size" value="1000" min="500" max="2000" required>
                                    <div class="form-text">每个文本块的最大字符数 (推荐: 1000)</div>
                                </div>
                                <div class="col-md-6">
                                    <label for="chunk_overlap" class="form-label">分块重叠</label>
                                    <input type="number" class="form-control" id="chunk_overlap" 
                                           name="chunk_overlap" value="200" min="0" max="500" required>
                                    <div class="form-text">相邻块之间的重叠字符数 (推荐: 200)</div>
                                </div>
                            </div>
                        </div>

                        <!-- 提交按钮 -->
                        <div class="text-center">
                            <button type="submit" class="btn btn-primary btn-lg" id="submit-btn">
                                <i class="bi bi-check-circle me-2"></i>完成配置并启动系统
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- 功能特性介绍 -->
            <div class="card config-card mt-4">
                <div class="card-header bg-success text-white text-center">
                    <h4 class="mb-0"><i class="bi bi-star-fill me-2"></i>系统特性</h4>
                </div>
                <div class="card-body">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="feature-item">
                                <i class="bi bi-search"></i>
                                <strong>智能搜索</strong>
                                <p class="mb-0 small">基于向量相似度的语义搜索，找到最相关的文档内容</p>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="feature-item">
                                <i class="bi bi-robot"></i>
                                <strong>AI问答</strong>
                                <p class="mb-0 small">集成本地AI模型，提供智能、准确的问答服务</p>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="feature-item">
                                <i class="bi bi-file-earmark-text"></i>
                                <strong>多格式支持</strong>
                                <p class="mb-0 small">支持PDF、Word、Excel、TXT、Markdown等多种文档格式</p>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="feature-item">
                                <i class="bi bi-lightning"></i>
                                <strong>快速处理</strong>
                                <p class="mb-0 small">高效的文档处理和向量化，支持大量文档管理</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// 显示帮助信息
function showHelp() {
    Swal.fire({
        title: '文档目录配置帮助',
        html: `
            <div class="text-start">
                <h6>📁 路径格式示例：</h6>
                <ul class="text-start">
                    <li><strong>Windows:</strong> C:\\Users\\YourName\\Documents</li>
                    <li><strong>macOS:</strong> /Users/YourName/Documents</li>
                    <li><strong>Linux:</strong> /home/YourName/documents</li>
                </ul>
                <hr>
                <h6>🔧 Docker环境说明：</h6>
                <p>在Docker环境中，您需要输入本地主机的文档目录路径。系统会自动建立卷映射关系，将您的本地目录挂载到容器内部。</p>
                <hr>
                <h6>📋 支持的文档格式：</h6>
                <ul class="text-start">
                    <li>PDF (.pdf)</li>
                    <li>Word (.docx)</li>
                    <li>Excel (.xlsx)</li>
                    <li>文本 (.txt)</li>
                    <li>Markdown (.md)</li>
                </ul>
            </div>
        `,
        icon: 'info',
        confirmButtonText: '明白了'
    });
}

// 路径验证
async function validatePath(path) {
    const validationDiv = document.getElementById('path-validation');
    const resultDiv = document.getElementById('validation-result');
    const fileCountDiv = document.getElementById('file-count');
    
    if (!path) {
        validationDiv.classList.add('d-none');
        return;
    }
    
    try {
        const response = await fetch('/api/validate-path', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ path: path })
        });
        
        const data = await response.json();
        
        validationDiv.classList.remove('d-none');
        
        if (data.valid) {
            resultDiv.innerHTML = `
                <div class="alert alert-success">
                    <i class="bi bi-check-circle me-2"></i>
                    <strong>路径有效</strong> - 目录存在且可访问
                </div>
            `;
            
            if (data.file_count > 0) {
                fileCountDiv.innerHTML = `
                    <div class="alert alert-info">
                        <i class="bi bi-file-earmark me-2"></i>
                        发现 <strong>${data.file_count}</strong> 个支持格式的文档文件
                    </div>
                `;
            } else {
                fileCountDiv.innerHTML = `
                    <div class="alert alert-warning">
                        <i class="bi bi-exclamation-triangle me-2"></i>
                        目录中未发现支持格式的文档文件
                    </div>
                `;
            }
        } else {
            resultDiv.innerHTML = `
                <div class="alert alert-danger">
                    <i class="bi bi-x-circle me-2"></i>
                    <strong>路径无效</strong> - ${data.error}
                </div>
            `;
            fileCountDiv.innerHTML = '';
        }
    } catch (error) {
        validationDiv.classList.remove('d-none');
        resultDiv.innerHTML = `
            <div class="alert alert-danger">
                <i class="bi bi-x-circle me-2"></i>
                <strong>验证失败</strong> - 无法验证路径
            </div>
        `;
        fileCountDiv.innerHTML = '';
    }
}

// 帮助按钮
document.getElementById('help-btn').addEventListener('click', function() {
    showHelp();
});

// 路径输入验证
document.getElementById('documents_path').addEventListener('input', function(e) {
    const path = e.target.value.trim();
    if (path) {
        validatePath(path);
    } else {
        document.getElementById('path-validation').classList.add('d-none');
    }
});

// 表单提交
document.getElementById('first-run-form').addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const submitBtn = document.getElementById('submit-btn');
    const originalText = submitBtn.innerHTML;
    
    submitBtn.disabled = true;
    submitBtn.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>配置中...';
    
    const formData = {
        documents_path: document.getElementById('documents_path').value.trim(),
        chunk_size: parseInt(document.getElementById('chunk_size').value),
        chunk_overlap: parseInt(document.getElementById('chunk_overlap').value)
    };
    
    try {
        const response = await fetch('/api/first-run-config', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify(formData)
        });
        
        const data = await response.json();
        
        if (response.ok) {
            // 显示成功消息
            Swal.fire({
                icon: 'success',
                title: '配置成功！',
                text: '系统配置已完成，正在启动...',
                showConfirmButton: false,
                timer: 2000
            }).then(() => {
                // 跳转到主页
                window.location.href = '/';
            });
        } else {
            throw new Error(data.error || '配置失败');
        }
    } catch (error) {
        Swal.fire({
            icon: 'error',
            title: '配置失败',
            text: error.message,
            confirmButtonText: '重试'
        });
        
        submitBtn.disabled = false;
        submitBtn.innerHTML = originalText;
    }
});

// 页面加载时检查是否已完成首次配置
window.addEventListener('load', async function() {
    try {
        const response = await fetch('/api/check-first-run');
        const data = await response.json();
        
        if (!data.first_run_required) {
            // 如果已完成配置，跳转到主页
            window.location.href = '/';
        }
    } catch (error) {
        console.error('检查首次运行状态失败:', error);
    }
});
</script>
{% endblock %} 